<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\Exception;
use think\exception\ValidateException;

use \PHPExcel;
use \PHPExcel_Style_Color;
use \PHPExcel_Style_Alignment;
use \PHPExcel_style_Fill;
use \PHPExcel_Style_Border;

use think\facade\Db;

use service\JsonService as Json;
use app\admin\controller\BaseController;

use app\common\model\User;
use app\common\model\UserWages;
use app\common\model\UserResume;
use app\common\model\ResumeRound;
use app\common\model\UserSectionLevel;
use app\common\model\Project;
use app\common\model\Job;
use app\common\model\JobRadioRecord;
use app\common\model\ResumeEducation;
use app\common\model\ResumeWork;
use app\common\model\UserSection;
use app\common\model\UserCompany;
use think\cache\driver\Redis;

use service\ChoiceService;

class RecordController extends BaseController
{
    /**
     * 公司性别
     */
    public function getCompanySex()
    {
        $data['sex_boy'] = User::where(['user.is_staff' => 1, 'user.status' => 1, 'resume.sex' => 1])
            ->alias('user')
            ->join('user_resume resume', 'user.id=resume.user_id')
            ->count();

        $data['sex_girl'] = User::where(['user.is_staff' => 1, 'user.status' => 1, 'resume.sex' => 2])
            ->alias('user')
            ->join('user_resume resume', 'user.id=resume.user_id')
            ->count();

        return Json::success('ok', $data);
    }

    /**
     * 公司职级
     */
    public function getCompanyLevel()
    {
        $data['director'] = User::getNum(['section_level_id' => UserSectionLevel::getVal(['level' => UserSectionLevel::min('level')], 'id')]);
        $data['staff']    = User::getNum(['section_level_id' => UserSectionLevel::getNum(['level' => UserSectionLevel::max('level')], 'id')]);

        return Json::success('ok', $data);
    }

    /**
     * 公司员工薪资
     */
    public function getCompanySalary()
    {
        $name = ['0-3000', '3000-4000', '4000-5000', '5000-6000', '6000-7000', '7000-8000', '8000-9000', '9000-10000', '10000-以上'];

        foreach($name as $k => &$number){
            list($numberLow, $numberHigh) = explode('-', $number);

            $where = [];
            if($numberLow > 0) $where[] = ['salary_total', '>=', $numberLow];
            if($numberHigh > 0) $where[] = ['salary_total', '<', $numberHigh];

            $num[] = UserWages::where($where)->whereMonth('create_time', 'last month')->count();

            if($numberLow > 0) $numberLow  = $numberLow / 1000 . 'k';
            if($numberHigh > 0) $numberHigh  = $numberHigh / 1000 . 'k';

            $name[$k] = $numberLow . '-' . $numberHigh;
        }

        return Json::success('ok', ['name' => $name, 'num' => $num]);
    }

    /**
     * 信息中心每日增长
     */
    public function getResumeToDayUp()
    {
        $todayNum = date('d');

        $dayArr = [];
        $staffIds = User::getCol(['is_staff' => 1], 'id');

        for($i = 1; $i <= $todayNum; $i++) $dayArr[] = $i;
        
        foreach($dayArr as $day){
            $num[] = UserResume::where([['user_id', 'not in', $staffIds], ['name', '<>', '']])->whereDay('create_time', date('Y-m') . '-' . $day)->count();
        }

        foreach($dayArr as &$day){
            $day .= '号';
        }

        return Json::success('ok', ['days' => $dayArr, 'day_num' => $num]);
    }

    /**
     * 信息中心学历
     */
    public function getResumeEducation()
    {
        $education = ['其他', '小学', '初中', '高中', '专科', '本科', '硕士', '博士'];
        
        $staffIds = User::getCol(['is_staff' => 1], 'id');

        foreach($education as $k => $day){
            $num[] = UserResume::where([['user_id', 'not in', $staffIds], ['education', '=', $k], ['name', '<>', '']])->count();
        }

        return Json::success('ok', ['name' => $education, 'num' => $num]);
    }

    /**
     * 信息中心工龄
     */
    public function getResumeJobNum()
    {
        $name = [0, 1, 2, 3, 4, 5, 6];

        foreach($name as $k => &$number){
            $where = [];
            $where[] = ['name', '<>', ''];
            $where[] = ['is_staff', '=', 0];

            if($number == 6){
                $where[] = ['job_num', '>=', $number];
            }else{
                $where[] = ['job_num', '=', $number];
            }

            $num[] = UserResume::where($where)->count();

            if($number == 0){
                $name[$k] = '1年以下';
            }else if($number == 6){
                $name[$k] = '5年以上';
            }else{
                $name[$k] .= '年';
            }
        }

        return Json::success('ok', ['name' => $name, 'num' => $num]);
    }

    /**
     * 信息中心年龄
     */
    public function getResumeAge()
    {
        $name = ['18-20', '20-22', '22-24', '24-26', '26-28', '28-30', '30-32', '32-34', '34-36', '36-以上'];
        $staffIds = User::getCol(['is_staff' => 1], 'id');

        foreach($name as $k => $number){
            list($low, $high) = explode('-', $number);

            $where = [];
            $where[] = ['user_id', 'not in', $staffIds];
            $where[] = ['name', '<>', ''];
            if($low > 0 && $high <= 0) $where[] = ['birthday', '<=', strtotime('-'. $low . ' year')];
            if($high > 0 && $low <= 0) $where[] = ['birthday', '>=', strtotime('-'. $high . ' year')];
            if($low > 0 && $high > 0) $where[] = ['birthday', 'between', [strtotime('-'. $high . ' year'), strtotime('-'. $low . ' year')]];

            $num[] = UserResume::where($where)->count();
            if($k != 9) $name[$k] .= '岁';
        }

        return Json::success('ok', ['name' => $name, 'num' => $num]);
    }

    /**
     * 信息中心性别
     */
    public function getResumeSex()
    {
        $staffIds = User::getCol(['is_staff' => 1], 'id');

        $data['boy']  = UserResume::where([['user_id', 'not in', $staffIds], ['sex', '=', 1], ['name', '<>', '']])->count();
        $data['girl'] = UserResume::where([['user_id', 'not in', $staffIds], ['sex', '=', 2], ['name', '<>', '']])->count();

        return Json::success('ok', $data);
    }

    /**
     * 信息中心薪资
     */
    public function getResumeSalary()
    {
        $name = ['0-3000', '3000-4000', '4000-5000', '5000-6000', '6000-7000', '7000-8000', '8000-9000', '9000-10000', '10000-以上'];

        foreach($name as $k => &$number){
            list($numberLow, $numberHigh) = explode('-', $number);

            $where = [];
            $where[] = ['name', '<>', ''];
            $where[] = ['is_staff', '=', 0];
            if($numberLow > 0) $where[] = ['wage_low', '>=', $numberLow];
            if($numberHigh > 0) $where[] = ['wage_low', '<', $numberHigh];

            $num[] = UserResume::where($where)->count();

            if($numberLow > 0) $numberLow  = $numberLow / 1000 . 'k';
            if($numberHigh > 0) $numberHigh  = $numberHigh / 1000 . 'k';

            $name[$k] = $numberLow . '-' . $numberHigh;
        }

        return Json::success('ok', ['name' => $name, 'num' => $num]);
    }



    /**
     * 我的团队
     */
    public function getMyTeam()
    {
        $sectionId  = Request()->param('section_id', 0);
        $searchName = Request()->param('search_name', '');

        $where[] = ['is_staff', '=', 1];
        $where[] = ['status', '=', 1];

        if($sectionId != 0) $where[] = ['section_id', '=', $sectionId];
    
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['id', 'in', $userIds];
        }
        
        $list = User::getList($where, 0, 0, 0, 'id, name, avatars');

        return Json::success('ok', $list);
    }

    /**
     * 交付中心-实时数据
     */
    public function getDeliverData()
    {
        $type        = Request()->param('type', 0);
        $sectionId   = Request()->param('section_id', 0);
        $userId      = Request()->param('user_id', 0);
        $searchName  = Request()->param('search_name', '');
        $date        = Request()->param('date', '');
        $isSign      = Request()->param('is_sign', 0);
        $signUserId  = Request()->param('sign_user_id', 0);
        if(empty($date)) $date = date('Y-m');

        $userIds = 0;
        $where   = [];

        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                if($isSign != 0){
                    $isUserRole = User::getUserRole($this->user_id);

                    if($signUserId && $isUserRole == 1){
                        $signUserIds = User::getCol(['section_id' => 6], 'id');
                        $signWhere = [['sign_user_id', 'in', $signUserIds]];
                    }else{
                        $signWhere = ['sign_user_id' => $this->user_id];
                    }

                    $companyIds = UserCompany::getCol($signWhere, 'id');
                    if(!$companyIds){
                        return Json::success('ok', [
                            'claim_num'  => 0,
                            'invite_num' => 0,
                            'pass_num'   => 0,
                            'join_num'   => 0,
                            'achie'      => 0,
                        ]);
                    }

                    $sectionWhere[] = ['company_id', 'in', $companyIds];
                }

                $sectionWhere[] = ['cate_id', '=', $type];

                $sectionIds = UserSection::getCol($sectionWhere, 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                $userIds = [$userId];
                $where[] = ['user_id', '=', $userId];
            }
        }
        
        $data['claim_num']  = ResumeRound::where($where)->where([['status', 'in', [1, 2, 3, 4, 5]]])->whereMonth('claim_time', $date)->count();
        $data['invite_num'] = ResumeRound::where($where)->where([['status', 'in', [2, 3, 4, 5]]])->whereMonth('invite_time', $date)->count();
        $data['pass_num']   = ResumeRound::where($where)->where([['status', 'in', [4, 5]]])->whereMonth('pass_time', $date)->count();
        $data['join_num']   = ResumeRound::where($where)->where([['status', '=', 5]])->whereMonth('join_time', $date)->count();
        $data['achie']      = Job::setAchie($userIds, $date);

        return Json::success('ok', $data);
    }

    /**
     * 交付中心-我的邀约
     */
    public function getDeliverMyData()
    {
        $type        = Request()->param('type', 0);
        $sectionId   = Request()->param('section_id', 0);
        $userId      = Request()->param('user_id', 0);
        $searchName  = Request()->param('search_name', '');
        $date        = Request()->param('date', '');
        $isSign      = Request()->param('is_sign', 0);
        $signUserId  = Request()->param('sign_user_id', 0);
        if(empty($date)) $date = date('Y-m');

        $todayNum = date('d');

        for($i = 1; $i <= $todayNum; $i++) $dayArr[] = $i;
        
        foreach($dayArr as $day){
            $where   = [];
            if(!empty($searchName)){
                $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                if($sectionId == 0 && $userId == 0){
                    if($isSign != 0){
                        $isUserRole = User::getUserRole($this->user_id);

                        if($signUserId && $isUserRole == 1){
                            $signUserIds = User::getCol(['section_id' => 6], 'id');
                            $signWhere = [['sign_user_id', 'in', $signUserIds]];
                        }else{
                            $signWhere = ['sign_user_id' => $this->user_id];
                        }
    
                        $companyIds = UserCompany::getCol($signWhere, 'id');
                        if(!$companyIds){
                            $claim[]  = 0;
                            $invite[] = 0;
                            $pass[]   = 0;
                            $join[]   = 0;

                            continue;
                        }

                        $sectionWhere[] = ['company_id', 'in', $companyIds];
                    }
    
                    $sectionWhere[] = ['cate_id', '=', $type];

                    $sectionIds = UserSection::getCol($sectionWhere, 'id');
                    $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                    $where[] = ['user_id', 'in', $userIds];
                }else if($sectionId != 0 && $userId == 0){
                    $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                    $where[] = ['user_id', 'in', $userIds];
                }else{
                    $userIds = $userId;
                    $where[] = ['user_id', '=', $userId];
                }
            }

            $claim[]  = ResumeRound::where($where)->where([['status', 'in', [1, 2, 3, 4, 5]]])->whereDay('claim_time', $date . '-' . $day)->count();
            $invite[] = ResumeRound::where($where)->where([['status', 'in', [2, 3, 4, 5]]])->whereDay('invite_time', $date . '-' . $day)->count();
            $pass[]   = ResumeRound::where($where)->where([['status', 'in', [4, 5]]])->whereDay('pass_time', $date . '-' . $day)->count();
            $join[]   = ResumeRound::where($where)->where([['status', '=', 5]])->whereDay('join_time', $date . '-' . $day)->count();
        }

        foreach($dayArr as &$day) $day .= '号';

        $data['claim']  = ['day' => $dayArr, 'data' => $claim];
        $data['invite'] = ['day' => $dayArr, 'data' => $invite];
        $data['pass']   = ['day' => $dayArr, 'data' => $pass];
        $data['join']   = ['day' => $dayArr, 'data' => $join];

        return Json::success('ok', $data);
    }

    /**
     * 交付中心-绩效目标
     */
    public function getDeliverAchie()
    {
        $type        = Request()->param('type', 0);
        $sectionId   = Request()->param('section_id', 0);
        $userId      = Request()->param('user_id', 0);
        $searchName  = Request()->param('search_name', '');
        $date        = Request()->param('date', '');
        $isSign      = Request()->param('is_sign', 0);
        $signUserId  = Request()->param('sign_user_id', 0);
        if(empty($date)) $date = date('Y-m');

        $todayNum = date('d');

        for($i = 1; $i <= $todayNum; $i++) $dayArr[] = $i;
        
        foreach($dayArr as $day){
            $where   = [];

            if(!empty($searchName)){
                $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                if($sectionId == 0 && $userId == 0){
                    if($isSign != 0){
                        $isUserRole = User::getUserRole($this->user_id);

                        if($signUserId && $isUserRole == 1){
                            $signUserIds = User::getCol(['section_id' => 6], 'id');
                            $signWhere = [['sign_user_id', 'in', $signUserIds]];
                        }else{
                            $signWhere = ['sign_user_id' => $this->user_id];
                        }
    
                        $companyIds = UserCompany::getCol($signWhere, 'id');
                        if(!$companyIds){
                            $totalAchieArr[] = 0;
                            $totalJoinArr[]  = 0;

                            continue;
                        }

                        $sectionWhere[] = ['company_id', 'in', $companyIds];
                    }
    
                    $sectionWhere[] = ['cate_id', '=', $type];

                    $sectionIds = UserSection::getCol($sectionWhere, 'id');
                    $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                    $where[] = ['user_id', 'in', $userIds];
                }else if($sectionId != 0 && $userId == 0){
                    $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                    $where[] = ['user_id', 'in', $userIds];
                }else{
                    $userIds = $userId;
                    $where[] = ['user_id', '=', $userId];
                }
            }

            $joinResumeList = ResumeRound::where($where)->where([['status', '=', 5]])->whereDay('join_time', $date . '-' . $day)->select();

            $totalAchie = 0;
            $totalJoin  = 0;
            foreach($joinResumeList as $info){
                $jobInfo = Job::getFind(['id' => $info['job_id']]);

                if($info['join_time'] < time() - 86400 * 5) $totalAchie += $jobInfo['total'];
                if($info['join_time'] < time() - 86400 * $jobInfo['warranty']) $totalJoin += $jobInfo['total'];
            }

            $totalAchieArr[] = $totalAchie;
            $totalJoinArr[]  = $totalJoin;
        }

        foreach($dayArr as &$day){
            $day .= '号';
        }

        $data['total_join']  = ['day' => $dayArr, 'data' => $totalJoinArr];
        $data['total_achie'] = ['day' => $dayArr, 'data' => $totalAchieArr];

        return Json::success('ok', $data);
    }

    /**
     * 交付中心-实时数据记录
     */
    public function getDeliverDataRecord()
    {
        $page        = Request()->param('page', 1);
        $type        = Request()->param('type', 0);
        $sectionId   = Request()->param('section_id', 0);
        $userId      = Request()->param('user_id', 0);
        $searchName  = Request()->param('search_name', '');
        $date        = Request()->param('date', '');
        $isSign      = Request()->param('is_sign', 0);
        $status      = Request()->param('status', 0);
        $signUserId  = Request()->param('sign_user_id', 0);
        if(empty($date)) $date = date('Y-m');

        $userIds = 0;
        $where   = [];

        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                if($isSign != 0){
                    $isUserRole = User::getUserRole($this->user_id);

                    if($signUserId && $isUserRole == 1){
                        $signUserIds = User::getCol(['section_id' => 6], 'id');
                        $signWhere = [['sign_user_id', 'in', $signUserIds]];
                    }else{
                        $signWhere = ['sign_user_id' => $this->user_id];
                    }

                    $companyIds = UserCompany::getCol($signWhere, 'id');
                    if(!$companyIds) return Json::fail('暂无数据');

                    $sectionWhere[] = ['company_id', 'in', $companyIds];
                }

                $sectionWhere[] = ['cate_id', '=', $type];

                $sectionIds = UserSection::getCol($sectionWhere, 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                $userIds = [$userId];
                $where[] = ['user_id', '=', $userId];
            }
        }

        switch ($status) {
            case 1:
                $where[] = ['status', 'in', [1, 2, 3, 4, 5]];
                break;
            case 2:
                $where[] = ['status', 'in', [2, 3, 4, 5]];
                break;
            case 3:
                $where[] = ['status', 'in', [4, 5]];
                break;
            case 4:
                $where[] = ['status', '=', 5];
                break;
            case 5:
                $where[] = ['status', '=', 5];
                break;
            default:
                $where[] = ['status', 'in', [1, 2, 3, 4, 5]];
                break;
        }

        $statusTime = [1 => 'claim_time', 2 => 'invite_time', 3 => 'pass_time', 4 => 'join_time', 5 => 'join_time'];

        $list = ResumeRound::where($where)->order($statusTime[$status] . ' DESC, id DESC')->limit(($page - 1) * 20, 20)->whereMonth($statusTime[$status], $date)->select();
        if($list->isEmpty()) return Json::fail('暂无数据');

        $statusName = [1 => '认领', 2 => '邀约', 3 => '到面', 4 => '通过', 5 => '入职', 6 => '未到面', 7 => '未通过', 8 => '未入职', 9 => '离职', 10 => '退回'];

        foreach($list as $info){
            /** 简历信息 */
            $resumeInfo = UserResume::getFind(['id' => $info['resume_id']]);

            /** 员工信息 */
            $userInfo = User::getFind(['id' => $info['user_id']]);

            /** 项目信息 */
            $projectInfo = Project::getFind(['id' => $info['project_id']]);

            /** 职位信息 */
            $jobInfo = Job::getFind(['id' => $info['job_id']]);

            /** 部门名称 */
            if($userInfo['section_id']){
                $sectionName = UserSection::getVal(['id' => $userInfo['section_id']], 'name');
                if($userInfo['section_level_id']) $sectionName .= '(' . UserSectionLevel::getVal(['id' => $userInfo['section_level_id']], 'name') . ')';
            }else{
                $sectionName = '';
            }

            /** 职位名称 */
            if($jobInfo){
                $jobName = $jobInfo['name'];
                if($projectInfo) $jobName .= '(' . $projectInfo['name'] . ')';
            }else{
                $jobName = '';
            }

            $backData[] = [
                'resume_name'  => $resumeInfo['name'],
                'staff_name'   => $userInfo['name'],
                'section_name' => $sectionName,
                'status'       => $statusName[$info['status']],
                'job_name'     => $jobName,
                'achie'        => $info['status'] == 5 ? Job::getTotal($info['job_id']) * JobRadioRecord::getJobRadio($info['job_id'], $info['join_time']) : 0,
                'status_time'  => date('Y-m-d H:i', $info[$statusTime[$info['status']]]),
            ];
        }

        return Json::success('ok', $backData, ResumeRound::where($where)->whereMonth($statusTime[$status], $date)->count());
    }



    /**
     * 员工档案
     */
    public function getUserResume()
    {
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');

        if($userId == 0 && !empty($searchName)) $userId = User::getVal([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');

        $info = UserResume::getFind(['user_id' => $userId]);
        if(!$info) return Json::fail('简历不存在');

        $userInfo      = User::getFind(['id' => $userId]);
        $workList      = ResumeWork::getList(['resume_id' => $info['id']], 0);
        $educationList = ResumeEducation::getList(['resume_id' => $info['id']], 0);

        /** 部门 */
        $info['section'] = UserSection::getVal(['id' => $userInfo['section_id']], 'name');
        $level = UserSectionLevel::getVal(['id' => $userInfo['section_level_id']], 'name');
        if($level) $info['section'] .= '-' . $level; 
        
        $info['birthday']       = $info['birthday'] ? date('Y-m-d', $info['birthday']) : '';
        $info['education_list'] = $educationList ? $educationList : [];
        $info['work_list']      = $workList ? $workList : [];
        $info['avatars']        = $userInfo['avatars'];
        $info['staff_no']       = $userInfo['staff_no'];
        $info['bank_num']       = $userInfo['card_num'];

        return Json::success('ok', $info);
    }



    /**
     * 商务中心-项目数据
     */
    public function getBusinJobData()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');

        $where   = [];
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                $where[] = ['user_id', '=', $userId];
            }
        }

        $data['today_num'] = Job::where($where)->whereDay('create_time')->count();
        $data['week_num']  = Job::where($where)->whereWeek('create_time')->count();
        $data['month_num'] = Job::where($where)->whereMonth('create_time')->count();
        $data['year_num']  = Job::where($where)->whereYear('create_time')->count();

        return Json::success('ok', $data);
    }

    /**
     * 商务中心-项目新增
     */
    public function getBusinJobAdd()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');

        $where   = [];
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                $userIds = $userId;
                $where[] = ['user_id', '=', $userId];
            }
        }

        $month = date('m');
        for($i = 1; $i <= $month; $i++) $monthArr[] = $i;

        foreach($monthArr as $month){
            $jobIds = Job::where($where)->whereMonth('create_time', date('Y') . '-' . $month)->column('id');

            $shareNum[] = UserResume::where([['job_id', 'in', $jobIds], ['source', '=', 1]])->whereMonth('create_time', date('Y') . '-' . $month)->count();
            $upNum[]    = UserResume::where([['job_id', 'in', $jobIds], ['source', '=', 2]])->whereMonth('create_time', date('Y') . '-' . $month)->count();
        }

        foreach($monthArr as &$day) $day .= '月';

        $data['share_num'] = ['day' => $monthArr, 'data' => $shareNum];
        $data['up_num']    = ['day' => $monthArr, 'data' => $upNum];

        return Json::success('ok', $data);
    }

    /**
     * 商务中心-项目有效性
     */
    public function getBusinJobValid()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');

        $where   = [];
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                $userIds = $userId;
                $where[] = ['user_id', '=', $userId];
            }
        }

        $month = date('m');
        for($i = 1; $i <= $month; $i++) $monthArr[] = $i;

        foreach($monthArr as $month){
            $jobList = Job::where($where)->whereMonth('create_time', date('Y') . '-' . $month)->select()->toArray();

            if(!$jobList){
                $valid[] = 0;
                continue;
            }

            $validNum = 0;
            foreach($jobList as $jobInfo){
                if(ResumeRound::where(['job_id' => $jobInfo['id'], 'status' => 5])->whereMonth('create_time', date('Y') . '-' . $month)->count() / $jobInfo['need_num'] >= 0.3) $validNum++;
            }

            $valid[] = rounding($validNum / count($jobList)) * 100;
        }

        foreach($monthArr as &$day) $day .= '月';

        $data = ['day' => $monthArr, 'data' => $valid];

        return Json::success('ok', $data);
    }

    /**
     * 商务中心-项目类型
     */
    public function getBusinJobType()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');

        $where   = [];
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['j.user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['j.user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['j.user_id', 'in', $userIds];
            }else{
                $userIds = $userId;
                $where[] = ['j.user_id', '=', $userId];
            }
        }

        $month = date('m');
        for($i = 1; $i <= $month; $i++) $monthArr[] = $i;

        foreach($monthArr as $month){
            $typeA[] = Job::where(['c.name' => 'A'])
                ->where($where)
                ->alias('j')
                ->join('job_cate c', 'c.id=j.cate_id')
                ->whereMonth('j.create_time', date('Y') . '-' . $month)
                ->count();

            $typeB[] = Job::where(['c.name' => 'B'])
                ->alias('j')
                ->join('job_cate c', 'c.id=j.cate_id')
                ->whereMonth('j.create_time', date('Y') . '-' . $month)
                ->count();

            $typeC[] = Job::where(['c.name' => 'C'])
                ->where($where)
                ->alias('j')
                ->join('job_cate c', 'c.id=j.cate_id')
                ->whereMonth('j.create_time', date('Y') . '-' . $month)
                ->count();

            $typeD[] = Job::where(['c.name' => 'D'])
                ->where($where)    
                ->alias('j')
                ->join('job_cate c', 'c.id=j.cate_id')
                ->whereMonth('j.create_time', date('Y') . '-' . $month)
                ->count();
        }

        foreach($monthArr as &$day) $day .= '月';

        $data['type_A'] = ['day' => $monthArr, 'data' => $typeA];
        $data['type_B'] = ['day' => $monthArr, 'data' => $typeB];
        $data['type_C'] = ['day' => $monthArr, 'data' => $typeC];
        $data['type_D'] = ['day' => $monthArr, 'data' => $typeD];

        return Json::success('ok', $data);
    }



    /**
     * 运营中心-数据
     */
    public function getJobResumeData()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');

        $where   = [];
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['share_user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['share_user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['share_user_id', 'in', $userIds];
            }else{
                $where[] = ['share_user_id', '=', $userId];
            }
        }

        $data['invite_num'] = UserResume::where($where)
            ->where([['claim_user_id', '>', 0]])
            ->whereMonth('create_time')
            ->count();

        $data['vaild_num']  = UserResume::alias('ur')
            ->where($where)
            ->where([['rr.status', '>=', 4]])
            ->whereMonth('ur.create_time')
            ->join('resume_round rr', 'ur.id=rr.resume_id')
            ->count();

        return Json::success('ok', $data);
    }

    /**
     * 运营中心-项目有效性
     */
    public function getJobResumeValid()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');

        $where[] = ['source', '=', 1];

        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['share_user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['share_user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['share_user_id', 'in', $userIds];
            }else{
                $where[] = ['share_user_id', '=', $userId];
            }
        }

        /** 认领数量 */
        $inviteNum = [];

        /** 认领有效数量 */
        $vaildNum = [];

        $todayNum = date('d');
        for($i = 1; $i <= $todayNum; $i++) $dayArr[] = $i;
        
        foreach($dayArr as $day){
            $inviteNum[] = UserResume::where($where)->where([['claim_user_id', '>', 0]])->whereDay('create_time', date('Y-m') . '-' . $day)->count();

            $vaildNum[]  = UserResume::alias('ur')
                ->where($where)
                ->where([['rr.status', '>=', 4]])
                ->whereDay('ur.create_time', date('Y-m') . '-' . $day)
                ->join('resume_round rr', 'ur.id=rr.resume_id')
                ->count();
        }

        foreach($dayArr as &$day) $day .= '号';

        $data['invite_num'] = ['day' => $dayArr, 'data' => $inviteNum];
        $data['vaild_num']  = ['day' => $dayArr, 'data' => $vaildNum];

        return Json::success('ok', $data);
    }



    /**
     * 供应商-薪酬
     */
    public function getSupplierSalary()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');
        $startTime  = Request()->param('start_time', '');
        $endTime    = Request()->param('end_time', '');

        $where   = [];
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                $userIds = $userId;
                $where[] = ['user_id', '=', $userId];
            }
        }

        $name = ['0-3000', '3000-4000', '4000-5000', '5000-6000', '6000-7000', '7000-8000', '8000-9000', '9000-10000', '10000-以上'];

        foreach($name as $number){
            list($numberLow, $numberHigh) = explode('-', $number);

            $whereSalary = [];

            if($numberLow > 0) $whereSalary[] = ['salary_low', '>=', $numberLow];
            if($numberHigh > 0) $whereSalary[] = ['salary_high', '<', $numberHigh];

            if(!empty($startTime) && !empty($endTime)){
                $whereSalary[] = ['create_time', 'between', [strtotime($startTime), strtotime($endTime)]];
                $num[] = Job::where($where)->where($whereSalary)->count();
            }else{
                $num[] = Job::where($where)->where($whereSalary)->whereMonth('create_time')->count();
            }
        }

        return Json::success('ok', ['name' => $name, 'num' => $num]);
    }

    /**
     * 供应商-保证期
     */
    public function getSupplierWarranty()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');
        $startTime  = Request()->param('start_time', '');
        $endTime    = Request()->param('end_time', '');

        $where   = [];
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                $userIds = $userId;
                $where[] = ['user_id', '=', $userId];
            }
        }

        $name = ['0-2', '2-4', '4-6', '6-8', '8-10', '10-12', '12-14', '14-16', '16-以上'];

        foreach($name as $number){
            list($numberLow, $numberHigh) = explode('-', $number);

            $whereWarranty = [];
            if($numberLow > 0) $whereWarranty[] = ['warranty', '>=', $numberLow];
            if($numberHigh > 0) $whereWarranty[] = ['warranty', '<', $numberHigh];

            if(!empty($startTime) && !empty($endTime)){
                $whereWarranty[] = ['create_time', 'between', [strtotime($startTime), strtotime($endTime)]];
                $num[] = Job::where($where)->where($whereWarranty)->count();
            }else{
                $num[] = Job::where($where)->where($whereWarranty)->whereMonth('create_time')->count();
            }
        }

        return Json::success('ok', ['name' => $name, 'num' => $num]);
    }

    /**
     * 供应商-返费
     */
    public function getSupplierTotal()
    {
        $type       = Request()->param('type', 0);
        $sectionId  = Request()->param('section_id', 0);
        $userId     = Request()->param('user_id', 0);
        $searchName = Request()->param('search_name', '');
        $startTime  = Request()->param('start_time', '');
        $endTime    = Request()->param('end_time', '');

        $where   = [];
        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
            $where[] = ['user_id', 'in', $userIds];
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => $type], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
                $where[] = ['user_id', 'in', $userIds];
            }else{
                $userIds = $userId;
                $where[] = ['user_id', '=', $userId];
            }
        }

        $name = ['0-500', '500-1000', '1000-1500', '1500-2000', '2000-2500', '2500-3000', '3000-3500', '3500-以上'];

        foreach($name as $number){
            list($numberLow, $numberHigh) = explode('-', $number);

            $whereTotal = [];
            if($numberLow > 0) $whereTotal[] = ['total', '>=', $numberLow];
            if($numberHigh > 0) $whereTotal[] = ['total', '<', $numberHigh];

            if(!empty($startTime) && !empty($endTime)){
                $whereTotal[] = ['create_time', 'between', [strtotime($startTime), strtotime($endTime)]];
                $num[] = Job::where($where)->where($whereTotal)->count();
            }else{
                $num[] = Job::where($where)->where($whereTotal)->whereMonth('create_time')->count();
            }
        }

        return Json::success('ok', ['name' => $name, 'num' => $num]);
    }



    /*********************************************** 我的账单 ************************************************ */
    /**
     * 我的账单-部门列表
     */
    public function getMoneySectionList()
    {
        return Json::success('ok', UserSection::getList(['cate_id' => 2], 0, 0, 0, 'id, name, brokerage_radio'));
    }

    /**
     * 我的账单-实时数据
     */
    public function getMoneyDeliverData()
    {
        $sectionId   = Request()->param('section_id', 0);
        $userId      = Request()->param('user_id', 0);
        $searchName  = Request()->param('search_name', '');
        $date        = Request()->param('date', '');
        $warranty    = Request()->param('warranty', 0);
        $warranty2   = Request()->param('warranty2', 0);

        $userIds = 0;
        $monthNow = strtotime(date('Y-m') . '-5');  /** 本月5号 */

        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => 2], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
            }else{
                $userIds = [$userId];
            }
        }

        if($userIds){
            $where = 'rr.user_id IN (' . implode(',', $userIds) . ')';
        }else{
            return Json::success('ok', [
                'claim_num'  => 0,
                'invite_num' => 0,
                'pass_num'   => 0,
                'join_num'   => 0,
                'achie'      => 0,
            ]);
        }
       

        switch ($warranty) {
            case 1:
                $where .= " and join_time > 0 and join_time < " . $monthNow . " - (warranty * 86400)";
                break;
            case 2:
                $where .= " and join_time >= " . $monthNow . " - (warranty * 86400) and join_time < " . time() . " - (warranty * 86400)";
                break;
            case 3:
                $where .= " and join_time > " . time() . " - (warranty * 86400)";
                break;
        }

        switch ($warranty2) {
            case 1:
                $where .= " and join_time > 0 and join_time < " . $monthNow . " - (warranty2 * 86400)";
                break;
            case 2:
                $where .= " and join_time >= " . $monthNow . " - (warranty2 * 86400) and join_time < " . time() . " - (warranty2 * 86400)";
                break;
            case 3:
                $where .= " and join_time > " . time() . " - (warranty2 * 86400)";
                break;
        }
           
        if(!empty($date)){
            $claimNum  = ResumeRound::alias('rr')
                ->join('user_resume ur', 'rr.resume_id=ur.id')
                ->join('user u', 'rr.user_id=u.id')
                ->join('job j', 'rr.job_id=j.id')
                ->join('project p', 'rr.project_id=p.id')
                ->where($where)
                ->where([['rr.status', 'in', [1, 2, 3, 4, 5]]])
                ->whereMonth('rr.claim_time', $date)
                ->count();

            $inviteNum = ResumeRound::alias('rr')
                ->join('user_resume ur', 'rr.resume_id=ur.id')
                ->join('user u', 'rr.user_id=u.id')
                ->join('job j', 'rr.job_id=j.id')
                ->join('project p', 'rr.project_id=p.id')
                ->where($where)
                ->where([['rr.status', 'in', [2, 3, 4, 5]]])
                ->whereMonth('rr.invite_time', $date)
                ->count();

            $passNum = ResumeRound::alias('rr')
                ->join('user_resume ur', 'rr.resume_id=ur.id')
                ->join('user u', 'rr.user_id=u.id')
                ->join('job j', 'rr.job_id=j.id')
                ->join('project p', 'rr.project_id=p.id')
                ->where($where)
                ->where([['rr.status', 'in', [4, 5]]])
                ->whereMonth('rr.pass_time', $date)
                ->count();

            $joinNum = ResumeRound::alias('rr')
                ->join('user_resume ur', 'rr.resume_id=ur.id')
                ->join('user u', 'rr.user_id=u.id')
                ->join('job j', 'rr.job_id=j.id')
                ->join('project p', 'rr.project_id=p.id')
                ->where($where)
                ->where([['rr.status', '=', 5]])
                ->whereMonth('rr.join_time', $date)
                ->count();

            $achie = Job::setAchie($userIds, $date); 
        }else{
            $claimNum  = ResumeRound::alias('rr')
                ->join('user_resume ur', 'rr.resume_id=ur.id')
                ->join('user u', 'rr.user_id=u.id')
                ->join('job j', 'rr.job_id=j.id')
                ->join('project p', 'rr.project_id=p.id')
                ->where($where)
                ->where([['rr.status', 'in', [1, 2, 3, 4, 5]]])
                ->count();

            $inviteNum = ResumeRound::alias('rr')
                ->join('user_resume ur', 'rr.resume_id=ur.id')
                ->join('user u', 'rr.user_id=u.id')
                ->join('job j', 'rr.job_id=j.id')
                ->join('project p', 'rr.project_id=p.id')
                ->where($where)
                ->where([['rr.status', 'in', [2, 3, 4, 5]]])
                ->count();

            $passNum = ResumeRound::alias('rr')
                ->join('user_resume ur', 'rr.resume_id=ur.id')
                ->join('user u', 'rr.user_id=u.id')
                ->join('job j', 'rr.job_id=j.id')
                ->join('project p', 'rr.project_id=p.id')
                ->where($where)
                ->where([['rr.status', 'in', [4, 5]]])
                ->count();

            $joinNum = ResumeRound::alias('rr')
                ->join('user_resume ur', 'rr.resume_id=ur.id')
                ->join('user u', 'rr.user_id=u.id')
                ->join('job j', 'rr.job_id=j.id')
                ->join('project p', 'rr.project_id=p.id')
                ->where($where)
                ->where([['rr.status', '=', 5]])
                ->count();

            $achie = Job::setAchie($userIds, $date);
        }

        $data = [
            'claim_num'  => $claimNum,
            'invite_num' => $inviteNum,
            'pass_num'   => $passNum,
            'join_num'   => $joinNum,
            'achie'      => $achie,
        ];

        return Json::success('ok', $data);
    }

    /**
     * 我的账单-实时数据记录
     */
    public function getMoneyDeliverDataRecord()
    {
        $page        = Request()->param('page', 1);
        $sectionId   = Request()->param('section_id', 0);
        $userId      = Request()->param('user_id', 0);
        $searchName  = Request()->param('search_name', '');
        $date        = Request()->param('date', '');
        $status      = Request()->param('status', 0);
        $warranty    = Request()->param('warranty', 0);
        $warranty2   = Request()->param('warranty2', 0);

        $userIds = 0;

        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => 2], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
            }else{
                $userIds = [$userId];
            }
        }

        $where = 'rr.user_id IN (' . implode(',', $userIds) . ')';

        switch ($status) {
            case 1:
                $where .= ' and rr.status IN (1,2,3,4,5)';
                break;
            case 2:
                $where .= ' and rr.status IN (2,3,4,5)';
                break;
            case 3:
                $where .= ' and rr.status IN (4,5)';
                break;
            case 4:
                $where .= ' and rr.status=5';
                break;
            case 5:
                $where .= ' and rr.status=5';
                break;
            default:
                $where .= ' and rr.status IN (1,2,3,4,5)';
                break;
        }

        $statusTimeField = [1 => 'claim_time', 2 => 'invite_time', 3 => 'pass_time', 4 => 'join_time', 5 => 'join_time'];
        $statusTime = [1 => 'claim_time', 2 => 'invite_time', 4 => 'pass_time', 5 => 'join_time'];

        /** 本月5号 */
        $monthNow = strtotime(date('Y-m') . '-5');

        $model = ResumeRound::alias('rr')
            ->join('user_resume ur', 'rr.resume_id=ur.id')
            ->join('user u', 'rr.user_id=u.id')
            ->join('job j', 'rr.job_id=j.id')
            ->join('project p', 'rr.project_id=p.id')
            ->field('
                rr.*, 
                ur.name as resume_name, 
                u.name as staff_name, 
                u.section_id, 
                j.name as job_name, 
                j.warranty, 
                p.name as project_name'
            )
            ->order($statusTimeField[$status] . ' DESC')
            ->limit(($page - 1) * 20, 20);

        if(!empty($date)){
            $endTime = strtotime('+1months', strtotime($date)) - 1;
            $where .= ' and ' . $statusTimeField[$status] . ' BETWEEN ' . strtotime($date) . ' and ' . $endTime;
        }

        switch ($warranty) {
            case 1:
                $where .= " and join_time > 0 and join_time < " . $monthNow . " - (warranty * 86400)";
                break;
            case 2:
                $where .= " and join_time >= " . $monthNow . " - (warranty * 86400) and join_time < " . time() . " - (warranty * 86400)";
                break;
            case 3:
                $where .= " and join_time > " . time() . " - (warranty * 86400)";
                break;
        }

        switch ($warranty2) {
            case 1:
                $where .= " and join_time > 0 and join_time < " . $monthNow . " - (warranty2 * 86400)";
                break;
            case 2:
                $where .= " and join_time >= " . $monthNow . " - (warranty2 * 86400) and join_time < " . time() . " - (warranty2 * 86400)";
                break;
            case 3:
                $where .= " and join_time > " . time() . " - (warranty2 * 86400)";
                break;
        }

        $list = $model->where($where)->select();
        if($list->isEmpty()) return Json::fail('暂无数据');

        foreach($list as &$info){
            if(!empty($info['job_name']) && !empty($info['project_name'])) $info['job_name'] .= '(' . $info['project_name'] . ')';

            $backData[] = [
                'resume_name'  => $info['resume_name'],
                'staff_name'   => $info['staff_name'],
                'section_name' => UserSection::getVal(['id' => $info['section_id']], 'name'),
                'status'       => ChoiceService::getResumeStatus($info['status']),
                'job_name'     => $info['job_name'],
                'achie'        => $info['status'] == 5 ? Job::getTotal($info['job_id']) * JobRadioRecord::getJobRadio($info['job_id'], $info['join_time']) : 0,
                'status_time'  => $info[$statusTime[$info['status']]] ? date('Y-m-d H:i', $info[$statusTime[$info['status']]]) : '',
            ];
        }

        $count = ResumeRound::alias('rr')
            ->join('user_resume ur', 'rr.resume_id=ur.id')
            ->join('user u', 'rr.user_id=u.id')
            ->join('job j', 'rr.job_id=j.id')
            ->join('project p', 'rr.project_id=p.id')
            ->where($where)
            ->count();
        return Json::success('ok', $backData, $count);
    }

    /**
     * 我的账单-导出
     */
    public function setMyMoneyOut()
    {
        $sectionId   = Request()->param('section_id', 0);
        $userId      = Request()->param('user_id', 0);
        $searchName  = Request()->param('search_name', '');
        $date        = Request()->param('date', '');
        $status      = Request()->param('status', 0);
        $warranty    = Request()->param('warranty', 0);
        $warranty2   = Request()->param('warranty2', 0);

        $userIds = 0;

        if(!empty($searchName)){
            $userIds = User::getCol([['name|staff_no', 'like', '%' . $searchName . '%']], 'id');
        }else{
            if($sectionId == 0 && $userId == 0){
                $sectionIds = UserSection::getCol(['cate_id' => 2], 'id');
                $userIds    = User::getCol([['section_id', 'in', $sectionIds]], 'id');
            }else if($sectionId != 0 && $userId == 0){
                $userIds = User::getCol([['section_id', '=', $sectionId]], 'id');
            }else{
                $userIds = [$userId];
            }
        }

        $where = 'rr.user_id IN (' . implode(',', $userIds) . ')';

        switch ($status) {
            case 1:
                $where .= ' and rr.status IN (1,2,3,4,5)';
                break;
            case 2:
                $where .= ' and rr.status IN (2,3,4,5)';
                break;
            case 3:
                $where .= ' and rr.status IN (4,5)';
                break;
            case 4:
                $where .= ' and rr.status=5';
                break;
            case 5:
                $where .= ' and rr.status=5';
                break;
            default:
                $where .= ' and rr.status IN (1,2,3,4,5)';
                break;
        }

        $statusTime = [1 => 'claim_time', 2 => 'invite_time', 3 => 'pass_time', 4 => 'join_time', 5 => 'join_time'];

        /** 本月5号 */
        $monthNow = strtotime(date('Y-m') . '-5');

        $model = ResumeRound::alias('rr')
            ->join('user_resume ur', 'rr.resume_id=ur.id')
            ->join('user u', 'rr.user_id=u.id')
            ->join('job j', 'rr.job_id=j.id')
            ->join('project p', 'rr.project_id=p.id')
            ->field('
                rr.*, 
                ur.name as resume_name, 
                u.name as staff_name, 
                u.section_id, 
                j.name as job_name, 
                j.warranty, 
                p.name as project_name'
            )
            ->order($statusTime[$status] . ' DESC');

        if(!empty($date)){
            $endTime = strtotime('+1months', strtotime($date)) - 1;
            $where .= ' and ' . $statusTime[$status] . ' BETWEEN ' . strtotime($date) . ' and ' . $endTime;
        }

        switch ($warranty) {
            case 1:
                $where .= " and join_time > 0 and join_time < " . $monthNow . " - (warranty * 86400)";
                break;
            case 2:
                $where .= " and join_time >= " . $monthNow . " - (warranty * 86400) and join_time < " . time() . " - (warranty * 86400)";
                break;
            case 3:
                $where .= " and join_time > " . time() . " - (warranty * 86400)";
                break;
        }

        switch ($warranty2) {
            case 1:
                $where .= " and join_time > 0 and join_time < " . $monthNow . " - (warranty2 * 86400)";
                break;
            case 2:
                $where .= " and join_time >= " . $monthNow . " - (warranty2 * 86400) and join_time < " . time() . " - (warranty2 * 86400)";
                break;
            case 3:
                $where .= " and join_time > " . time() . " - (warranty2 * 86400)";
                break;
        }

        $list = $model->where($where)->select();
        if($list->isEmpty()) return Json::fail('暂无数据');

        /** 实例化 */
        $objExcel = new \PHPExcel();

        /** 设置文档属性 */
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        /** 创建表 */
        $objExcel->setActiveSheetIndex(0);

        /** 设置内容 */
        $objActSheet = $objExcel->getActiveSheet();

        $fieldList = ['用户名称', '员工名称', '员工部门', '状态', '职位名称', '业绩', '时间'];

        $number = count($fieldList);
        $letter = getLetter($number);

        /** 填充表头信息 */
        for($i = 0; $i < $number; $i++) $objActSheet->setCellValue("$letter[$i]1", "$fieldList[$i]");

        /** 全部格式 */
        $objActSheet->getDefaultColumnDimension()->setWidth(20);  /** 所有单元格（列）默认宽度 */
        $objActSheet->getStyle('A1:' . $letter[count($fieldList) - 1] . (count($list) + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);  /** 水平居中 */
        $objActSheet->getStyle('A1:' . $letter[count($fieldList) - 1] . (count($list) + 1))->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);  /** 垂直居中 */

        /** 标题栏格式 */
        $objActSheet->getStyle('A1:' . $letter[count($fieldList) - 1] . '1')->getFont()->setBold(true);  /** 加粗 */
        $objActSheet->getStyle('A1:' . $letter[count($fieldList) - 1] . '1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);  /** 填充颜色 */
        $objActSheet->getStyle('A1:' . $letter[count($fieldList) - 1] . '1')->getFill()->getStartColor()->setARGB('FFFFCC');  /** 设置填充颜色 */
        $objActSheet->getRowDimension('1')->setRowHeight(30);  /** 设置行高度 */

        $objActSheet->freezePane('B2');  /** 冻结 */
        $objActSheet->setTitle('原始数据');  /** sheet重命名 */

        /** 设置边框 */
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => PHPExcel_Style_Border::BORDER_THIN,  /** 细边框 */
                ),
            ),
        );
        $objActSheet->getStyle('A1:' . $letter[count($fieldList) - 1] . (count($list) + 1))->applyFromArray($styleArray);

        /** 填充表格信息 */
        foreach($list as $kk => $info){
            $kk += 2;

            if(!empty($info['job_name']) && !empty($info['project_name'])) $info['job_name'] .= '(' . $info['project_name'] . ')';
            
            /** 表格内容 */
            $objActSheet->setCellValue('A' . $kk, $info['resume_name']);  /** 用户名称 */
            $objActSheet->setCellValue('B' . $kk, $info['staff_name']);  /** 员工名称 */
            $objActSheet->setCellValue('C' . $kk, UserSection::getVal(['id' => $info['section_id']], 'name'));  /** 员工部门 */
            $objActSheet->setCellValue('D' . $kk, ChoiceService::getResumeStatus($info['status']));  /** 状态 */
            $objActSheet->setCellValue('E' . $kk, $info['job_name']);  /** 职位名称 */
            $objActSheet->setCellValue('F' . $kk, $info['status'] == 5 ? Job::getTotal($info['job_id']) * JobRadioRecord::getJobRadio($info['job_id'], $info['join_time']) : 0);  /** 业绩 */
            $objActSheet->setCellValue('G' . $kk, date('Y-m-d H:i', $info[$statusTime[$info['status']]]));  /** 时间 */

            $objActSheet->getRowDimension($kk)->setRowHeight(30);  /** 表格高度 */
        }
 
        $outfile = "我的账单-" . date('Y-m-d H:i:s') . ".xlsx";

        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:attachment;filename="' . $outfile . '"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");

        $objWriter->save('php://output', true);
    }
    /*********************************************** 我的账单 ************************************************ */
}